<template>
  <el-dialog append-to-body v-model="dialogVisible" title="客房列表" width="70%">
    <el-button @click="handleAdd"  class="button-header"  type="primary" :icon="Plus">添加客房</el-button>
    <el-form inline :model="query" class="filter" label-width="100px">
    <el-form-item label="客房名称：">
      <el-col :span="22">
        <el-input v-model="query.name" placeholder="请输入客房名称：" />
      </el-col>
    </el-form-item>
    <el-form-item class="filter-actions">
      <el-button class="button-small" type="primary" @click="handleSearch">筛选</el-button>
      <el-button type="text" class="button-reset" @click="handleClear">重置筛选条件</el-button>
    </el-form-item>
    </el-form>
    <el-table :data="tableData" @sort-change="handleSortChange">
      <el-table-column prop="name" label="客房名称" />
      <el-table-column prop="area" sortable label="酒店面积( m²)" />
      <el-table-column prop="bedType" label="床类型" width="200">
        <template #default="scope">
          <el-tag class="mr-10" v-if="scope.row.bedType & BedType.Big">大床</el-tag>
          <el-tag  class="mr-10" v-if="scope.row.bedType & BedType.Double">双人床</el-tag>
          <el-tag v-if="scope.row.bedType & BedType.Single">单人床</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="internetType" label="上网方式">
        <template #default="scope">
          <el-tag  class="mr-10" v-if="scope.row.internetType & InternetType.WIFI">WIFI</el-tag>
          <el-tag v-if="scope.row.internetType & InternetType.Wired">有线宽带</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="windowType" label="窗户类型" />
      <el-table-column prop="price" sortable label="价格" />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column label="排序" width="180" sortable prop="sequence">
        <template #default="scope">
          <el-input-number v-model="scope.row.sequence" controls-position="right" @change="handleChangeSequence(scope.row)" :min="0" :max="99999999" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right" width="200">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-popconfirm :width="200" class="btn-popconfirm" @confirm="handleDelete(scope.row.id)" confirmButtonText="确认" cancelButtonText="取消" title="确定要删除该场地吗？">
            <template #reference>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <el-dialog append-to-body :title="postForm.title" v-model="postForm.dialogVisible" width="850px">
    <el-form ref="postFormRef" label-width="150px" class="ruleForm" :model="postForm.form" :rules="postForm.rules">
      <el-form-item label="客房名称：" prop="name">
        <el-col :span="22">
          <el-input v-model="postForm.form.name" maxlength="20" show-word-limit placeholder="请输入客房名称" />
        </el-col>
      </el-form-item>
      <el-form-item label="床型：" prop="bedType"> 
        <el-col :span="22">
          <el-select  multiple v-model="bedTypes" placeholder="请选择床型" filterable>
            <el-option label="大床" :value="BedType.Big" />
            <el-option label="双人床" :value="BedType.Double" />
            <el-option label="单人床" :value="BedType.Single" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="上网方式：" prop="bedType"> 
        <el-col :span="22">
          <el-select  multiple v-model="internetTypes" placeholder="请选择上网方式" filterable>
            <el-option label="WIFI" :value="InternetType.WIFI" />
            <el-option label="有线宽带" :value="InternetType.Wired" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="窗户：" prop="windowType"> 
        <el-col :span="22">
          <el-select   v-model="postForm.form.windowType" placeholder="请选择窗户" >
            <el-option label="有窗" :value="WindowType.Have" />
            <el-option label="无窗" :value="WindowType.None" />
            <el-option label="部分有窗" :value="WindowType.Partial" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="面积：" prop="area">
        <el-col :span="22">
          <el-input-number v-model="postForm.form.area" :precision="2" :min="0" controls-position="right" /> m²
        </el-col>
      </el-form-item>
      <el-form-item label="楼层：">
        <el-col :span="22">
          <el-input-number v-model="postForm.form.minFoor" :min="0" controls-position="right" />
            <span class="ml-10 mr-10"> - </span>
          <el-input-number v-model="postForm.form.maxFoor" :min="0" controls-position="right" />
        </el-col>
      </el-form-item>
      <el-form-item label="价格：" prop="price">
        <el-col :span="22">
          ￥ <el-input-number v-model="postForm.form.price" :precision="2" :min="0" controls-position="right" />
        </el-col>
      </el-form-item>
      <el-form-item label="数量：" prop="quantity">
        <el-col :span="22">
          ￥ <el-input-number v-model="postForm.form.quantity" :precision="2" :min="0" controls-position="right" />
        </el-col>
      </el-form-item>
      <el-form-item label="图片：" prop="images">
        <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="postForm.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave(postFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { GetGuests,GuestSave,GetGuestDetails,GuestRoomDelete,UpdateGuestSequence } from '@/api/site'
import { ElMessage, ElForm } from 'element-plus'
import { BedType, InternetType ,WindowType} from '@/utils/enum'
import ChooseFile from '@/components/ChooseFile.vue'
interface Props {
  visible: boolean,
  venueId:number,
}
const props = withDefaults(defineProps<Props>(), {
  visible:false,
  venueId:0,
})
/**
 * 选中的床型
 */
const bedTypes = ref<number[]>([])
/**
 * 选中的网络
 */
const internetTypes = ref<number[]>([])

/**
 * 床型验证
 * @param rule 
 * @param value 
 * @param callback 
 */
const validateBed = (rule: any, value: any, callback: any) => {
  if(bedTypes.value.length === 0) {
    return callback(new Error('请选择床型'))
  }
  callback()
}
/**
 * 网络验证
 * @param rule 
 * @param value 
 * @param callback 
 */
const validateInternetType = (rule: any, value: any, callback: any) => {
  if(internetTypes.value.length === 0) {
    return callback(new Error('请选择上网方式'))
  }
  callback()
}
/**
 * 客房编辑模型
 */
const postForm = ref<DialogForm<GuestRoomEdit>>({
  dialogVisible: false, 
  title:'添加酒店',
  form: {
    id: 0,
    venueId: 0,
    name:'',
    bedType: undefined,
    internetType: undefined,
    windowType: undefined,
    area:0 ,
    price: 0,
    quantity: 1,
    images: [],
    minFoor: 0,
    maxFoor: 0
  },
  rules: {
    name: [{ required: true, message: '请输入客房名称', trigger: 'blur' }],
    windowType: [{ required: true, message: '请选择窗型', trigger: 'change' }],
    Price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
    quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
    images: [{ type: 'array', required: true, message: '请上传图片', trigger: 'change' }],
    bedType: [{ type: 'array', required: true, validator: validateBed, trigger: 'change' }],
    internetType: [{ type: 'array', required: true, validator: validateInternetType , trigger: 'change' }],
  }
})

/**
 * 查询条件
 */
 const query = reactive({
  /**
   * 客房名称
   */
  name:''
})
let isAsc = false
let sortName = 'sequence'
/**
 * 客房列表
 */
 const tableData = ref<GuestRoom[]>([])
 type FormInstance = InstanceType<typeof ElForm>
 const postFormRef = ref<FormInstance>()
/**
 * 点击添加客房
*/
 const handleAdd = ():void => {
  postForm.value.dialogVisible = true
  postForm.value.title = '添加客房' 
  postForm.value.form.id = 0
  postForm.value.form.venueId = props.venueId
  postForm.value.form.name = ''
  postForm.value.form.bedType = undefined
  postForm.value.form.internetType = undefined
  postForm.value.form.windowType = undefined
  postForm.value.form.area = 0
  postForm.value.form.price = 0   
  postForm.value.form.quantity = 1
  postForm.value.form.minFoor = 0
  postForm.value.form.maxFoor = 0
  postForm.value.form.images = []
}
/**
 * 点击修改
 * @param formEl 
 */
 const handleEdit = (id:number):void => {
  postForm.value.form.id = id
  postForm.value.dialogVisible = true
  postForm.value.title = '编辑客房'
  GetGuestDetails(postForm.value.form.id).then((res:ServiceResponse<GuestRoomEdit>) => {
    if(res.success) {
      postForm.value.form = res.data ?? postForm.value.form
      if(postForm.value.form.bedType) {
        bedTypes.value = []
        if(postForm.value.form.bedType & BedType.Big) {
          bedTypes.value.push(BedType.Big)
        }
        if(postForm.value.form.bedType & BedType.Double) {
          bedTypes.value.push(BedType.Double)
        }
        if(postForm.value.form.bedType & BedType.Single) {
          bedTypes.value.push(BedType.Single)
        }
      }
      if(postForm.value.form.internetType) {
        internetTypes.value = []
        if(postForm.value.form.internetType & InternetType.WIFI) {
          internetTypes.value.push(InternetType.WIFI)
        }
        if(postForm.value.form.internetType & InternetType.Wired) {
          internetTypes.value.push(InternetType.Wired)
        }
      }
    }
  })
}
/**
 * 搜索
 * @param row 
 */
 const handleSearch = ():void => {
  loadData()
}

/**
 * 重置
 */
const handleClear = (): void => {
  query.name = ''
  loadData()
}
const handleSortChange = (data: any) => {
  sortName = data.prop
  isAsc = data.order === 'ascending'
  SortTableData()
}
const SortTableData = ():void => {
   switch(sortName)
   {
    case 'sequence':
      if(isAsc) 
          tableData.value =tableData.value.sort(function(a, b) { return a.sequence - b.sequence })
        else
          tableData.value =tableData.value.sort(function(a, b) { return b.sequence - a.sequence })
      break
      case 'area':
      if(isAsc) 
            tableData.value =tableData.value.sort(function(a, b) { return a.area - b.area })
          else
            tableData.value =tableData.value.sort(function(a, b) { return b.area - a.area })
      break
      case 'price':
      if(isAsc) 
            tableData.value =tableData.value.sort(function(a, b) { return a.price - b.price })
          else
            tableData.value =tableData.value.sort(function(a, b) { return b.price - a.price })
        break
   }
}
/**
 * 删除
 * @param formEl 
 */
 const handleDelete = (id:number):void => {
  GuestRoomDelete(id).then(((res:ServiceResponse<any>) => {
    if(res.success) {
          ElMessage.success('删除成功')
          loadData()
        } else  ElMessage.error(res.msg)
  }))
}

/**
 * 保存
 * @param formEl 
 */
 const handleSave = (formEl: FormInstance | undefined): void => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      let bedType = 0
      bedTypes.value.forEach((item:number) => {
        bedType |= item
      })
      postForm.value.form.bedType = bedType
      let internetType = 0
      internetTypes.value.forEach((item:number) => {
        internetType |= item
      })
      postForm.value.form.internetType = internetType
      GuestSave(postForm.value.form).then((res:ServiceResponse<any>) => {
        if(res.success) {
          ElMessage.success('保存成功')
          loadData()
          postForm.value.dialogVisible = false
        } else if(res.msg) {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

/**
 * 修改排序
 * @param row 
 */
 const handleChangeSequence = (row:Brand):void => {
  UpdateGuestSequence(row.id,row.sequence).then((res:ServiceResponse<any>) => {
    if(res.success) {
          ElMessage.success('保存成功')
          loadData()
        } else  ElMessage.error(res.msg)
  })
}

 /**
  * 加载数据
  */
  const loadData = ():void => {
    GetGuests(props.venueId, query.name).then((res:ServiceResponse<GuestRoom[]>) => {
    if(res.success) {
      tableData.value = res.data ?? []
      SortTableData()
    }
  })
}
/**
 * 监听dialogVisible变化
 */
 watch(()=>props.visible,() => {
  loadData()
})
interface Emits {
     (e: 'update:visible', dialogVisible: boolean): void,
     (e: 'on-confirm'): void
}
const emit = defineEmits<Emits>()
const dialogVisible = computed(
 {
   get() {
      return props.visible
    },
    set(visible: boolean) {
     
      emit('update:visible', visible)
      emit('on-confirm')
    }
 }
)
</script>
<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/tablePage.scss";
.ml-10 {
  margin-left: 10px;
}
.mr-10 {
  margin-right: 10px;
}
</style>